package net.sureon.app;

import java.util.Locale;

import net.sureon.common.I18nSupport;
import net.sureon.common.security.Role;

import org.springframework.context.ApplicationContext;

/**
 * the application context, we will set that for each logged in users, and we
 * will reset it after the execution.
 * 
 * @author jason
 * 
 */
public class AppContext {
	private static ThreadLocal<Locale> currentLocale = new ThreadLocal<Locale>();
	private static ThreadLocal<UserSession> currentUserSession = new ThreadLocal<UserSession>();
	private static ThreadLocal<ApplicationContext> currentSpringAppContext = new ThreadLocal<ApplicationContext>();
	
	public static Locale getLocale() {
		Locale current = currentLocale.get();
		return (current == null) ? I18nSupport.defaultLocale : current;
	}

	public static void setLocale(Locale locale) {
		currentLocale.set(locale);
	}

	public static UserSession getCurrentUserSession() {
		return currentUserSession.get();
	}

	public static void setCurrentUserSession(UserSession session) {
		currentUserSession.set(session);
	}
	
	public static ApplicationContext getCurrentSpringAppContext() {
		return currentSpringAppContext.get();
	}

	public static void setCurrentSpringAppContext(ApplicationContext appContext) {
		currentSpringAppContext.set(appContext);
	}	

	public static long getCompanyID() {
		UserSession sess = getCurrentUserSession();
		if (sess != null) {
			return sess.getCompanyID();
		}
		return 0;
	}

	public static long getUserID() {
		UserSession sess = getCurrentUserSession();
		if (sess != null) {
			return sess.getUserID();
		}
		return 0;
	}
	
    public static boolean isRootLogin() {
        UserSession sess = getCurrentUserSession();
        if (sess != null) {
            return sess.isRootLogin();
        }
        return false;
    }	
	
	public static long getGroupID() {
		UserSession sess = getCurrentUserSession();
		if (sess != null) {
			return sess.getGroupID();
		}
		return 0;
	}

	public static Role getRole() {
		UserSession sess = getCurrentUserSession();
		if (sess != null) {
			return sess.getRole();
		}
		return null;
	}
	
	public static void reset(){
		setLocale(null);
		setCurrentUserSession(null);
	}
}
